package com.geezdata.cps.base.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StringUtil {
	private static final Logger logger = LoggerFactory.getLogger(StringUtil.class);

	//从淘宝获取的数据中有可能会有特殊字符，在执行同步时会产生错误，需要将特殊字符替换
    public static String replaceSpecialChar(String originalString) {
        try {
            if (originalString != null) {
                return originalString.replace((char) 8, '%').replace("%", "");
            } else {
                return "";
            }
        } catch (Exception e) {
            logger.error("", e);
        }
        return originalString;
    }
    
    public static boolean isMobile(String mobile) {
    	if(StringUtils.isEmpty(mobile)) {
    		return false;
    	}
    	
    	Pattern p = Pattern.compile("^1(3[0-9]|4[57]|5[0-35-9]|6[6]|7[0135678]|8[0-9]|9[89])\\d{8}$");
    	Matcher m = p.matcher(mobile);
    	return m.matches();
    }
    
    public static boolean isContainChinese(String str) {
    	if(StringUtils.isEmpty(str)) {
    		return false;
    	}
    	
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        return m.find();
    }
    
    public static String encodeMobile(String number) {
        int encnum = Integer.parseInt(number.substring(2));
        int prefix = (number.charAt(1) - '2') /2;   // '3'=>0, '5'=>1, '[67]'=>2, '8'=>3
        encnum |= (prefix <<= 30);
        final byte[] raw = new byte[4];
        raw[0] = (byte)(encnum >>> 24);
        raw[1] = (byte)(encnum >>> 16);
        raw[2] = (byte)(encnum >>> 8);
        raw[3] = (byte) encnum;
        return Base64.encodeBase64URLSafeString(raw);
    }

    public static String decodeMobile(String encoded) {
        final byte[] raw = Base64.decodeBase64(encoded);
        int encnum = (raw[0]) << 24
            | ((raw[1] & 0xFF) << 16)
            | ((raw[2] & 0xFF) << 8)
            |  (raw[3] & 0xFF);
        StringBuilder number = new StringBuilder(11);
        number.append('1');
        final char[] prefix = {'3','5','6','8'};
        number.append(prefix[encnum >>> 30]);
        String suffix = Integer.toString(encnum & ~(3<<30));
        int pad = 9 - suffix.length();
        if (pad > 0) {
            final char[] padding = {'0','0','0','0','0','0','0','0'}; // max 8 '0's
            number.append(padding, 0, pad);
        }
        number.append(suffix);
        return number.toString();
    }
    
    public static Integer getMessageQuantity(String content) {
		return (content.length()/69) + ((content.length()%69 != 0) ? 1: 0 );
	}
}
